import logging
from apps.models.t_dev_data_model import TDevData


class TDevDataRepository:
    """
    DevData 数据访问仓库类
    """
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)

    def create_dev_data(self, data_type, data_id, dev_id, reg_id, data_value, data_time):
        """
        创建新的设备数据记录
        """
        dev_data = TDevData(
            data_type=data_type,
            data_id=data_id,
            dev_id=dev_id,
            reg_id=reg_id,
            data_value=data_value,
            data_time=data_time
        )
        dev_data.save(using='result')
        return dev_data

    def get_dev_data_by_id(self, pk):
        """
        根据ID获取设备数据记录
        """
        try:
            return TDevData.objects.using('result').get(id=pk)
        except TDevData.DoesNotExist:
            return None

    def get_all_dev_data(self):
        """
        获取所有设备数据记录
        """
        return TDevData.objects.using('result').all()

    def update_dev_data(self, pk, **kwargs):
        """
        更新设备数据记录
        """
        dev_data = self.get_dev_data_by_id(pk)
        if dev_data:
            for key, value in kwargs.items():
                setattr(dev_data, key, value)
            dev_data.save(using='result')
            return dev_data
        return None

    def delete_dev_data(self, pk):
        """
        删除设备数据记录
        """
        dev_data = self.get_dev_data_by_id(pk)
        if dev_data:
            dev_data.delete()
            return True
        return False

    def get_dev_data_by_condition(self, data_type, dev_id, start_time, end_time):
        """
        根据条件获取设备数据记录
        """
        queryset = TDevData.objects.using('result').all()
        if data_type:
            queryset = queryset.filter(data_type=data_type)
        if dev_id:
            queryset = queryset.filter(dev_id=dev_id)
        if start_time and end_time:
            queryset = queryset.filter(data_time__range=(start_time, end_time))
        elif start_time:
            queryset = queryset.filter(data_time__gte=start_time)
        elif end_time:
            queryset = queryset.filter(data_time__lte=end_time)
        queryset.order_by('data_time')
        return queryset